package com.xinyue.network.message.stream;

import com.google.protobuf.GeneratedMessageV3;
import com.google.protobuf.GeneratedMessageV3.Builder;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Message;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.CompositeByteBuf;
import io.netty.buffer.Unpooled;

public abstract class AbstractGameMessage implements IGameMessage {

    private IMessageHeader header;
    protected String messageDesc;
    private Message body;

    public AbstractGameMessage() {
        GameMessageMetadata gameMessageMetaData = this.getClass().getAnnotation(GameMessageMetadata.class);
        if (gameMessageMetaData == null) {
            throw new IllegalArgumentException("消息没有添加元数据注解：" + this.getClass().getName());
        }
        header = this.createHeader();
        header.setMessageId(gameMessageMetaData.messageId());
        header.setGameModuleId(gameMessageMetaData.serviceId());
        header.setMessageType(gameMessageMetaData.messageType());
        this.messageDesc = gameMessageMetaData.desc();
    }


    @Override
    public IMessageHeader getHeader() {
        return header;
    }
    

    @Override
    public ByteBuf write() {
    	//保存消息包的总大小
    	ByteBuf totalSizeBuf = Unpooled.buffer(4);
    	//序列化之后的包头信息
        ByteBuf headerBuf = this.header.write();
        Builder<?> builder = this.getMessageBuilder();
        ByteBuf bodyBuf = null;
        //包体总大小 = 总大小占用字节数 + 包头字节数 + 包体字节数
        int total = 4 + headerBuf.readableBytes();
        //获取序列化之后包休信息
        if (builder != null) {
        	body = builder.build();
        	
            byte[] bodyBtes = builder.build().toByteArray();
            total += bodyBtes.length;
            bodyBuf = Unpooled.wrappedBuffer(bodyBtes);
        }
        totalSizeBuf.writeInt(total);
        //使用组合buf将三个ByteBuf组合起来，可以减少复制次数
        CompositeByteBuf byteBuf = Unpooled.compositeBuffer();
        byteBuf.addComponent(true,totalSizeBuf);
        byteBuf.addComponent(true,headerBuf);
        if (bodyBuf != null) {
            byteBuf.addComponent(true,bodyBuf);
        }
        return byteBuf;
    }

    public GeneratedMessageV3.Builder<?> getMessageBuilder() {
        // 子类根据实际情况决定是否实现
        return null;
    }

    protected void parseFrom(byte[] bytes) throws InvalidProtocolBufferException {
        // 子类根据实际情况决定是否实现
    }

    @Override
    public void read(ByteBuf byteBuf) throws InvalidProtocolBufferException {
        this.header.read(byteBuf);
        if (byteBuf.isReadable()) {
            byte[] bytes = new byte[byteBuf.readableBytes()];
            byteBuf.readBytes(bytes);
            this.parseFrom(bytes);
        }
    }

    protected abstract IMessageHeader createHeader();


	@Override
	public String toString() {
		return "发送消息 [header=" + header + ", messageDesc=" + messageDesc + ", body=" + body + "]";
	}
    
    
}
